<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 * 行为控制器
 * @author huajie <banhuajie@163.com>
 */
class RelationController extends AdminController {
    /**
     * @author Scor
     * 业务信息
     */
    public function index(){
        $phone = I('user_phone');
        $saler = I('saler');
        $street = I('street');
        $realname = I('realname');
        $shop = I('shop');
        $map="";
        if ($phone) {
            $map['phone']=array('like','%'.$phone.'%');
        }
        if ($realname) {
            $map['realName']=array('like','%'.$realname.'%');
        }
        if ($saler) {
            $salerName['sname']=array('like','%'.$saler.'%');
            $resultUid=M("relationship")->where($salerName)->getField("uid",true);
            $map['id']=array("in",$resultUid);
        }
        if ($street) {
            $map['street']=array('like','%'.$street.'%');
        }
        if ($shop) {
            $map['shopName']=array('like','%'.$shop.'%');
        }
        $customersList = $this->listsM('buyers',$map,"id asc");
        if($customersList){
            for($i=0;$i<count($customersList);$i++){
                $map2['uid']=$customersList[$i]['id'];
                $res =M('relationship')->where($map2)->find();
                if($res){
                    $customersList[$i]['sname']=$res['sname'];
                }else{
                    $customersList[$i]['sname']="";
                }
            }
        }
        $this->assign("buyers",$customersList);
        $this->display();
    }
    public function export(){
        $sql = " select id,realName,phone,city,street,shopName,amount,from_unixtime(createdate) from gr_buyers  where 1=1 ";
        $phone = I('user_phone');
        $saler = I('saler');
        $street = I('street');
        $realname = I('realname');
        $shop = I('shop');
        $map = "";

        if ($phone) {
            $sql .= " and phone like '%" . $phone . "%'";
        }
        if ($realname) {
            $sql .= " and realName like '%" . $realname . "%'";
        }
        if ($saler) {
            $salerName['sname']=array('like','%'.$saler.'%');
            $resultUid=M("relationship")->where($salerName)->getField("uid",true);
            $uidstr = '(';
            for($i=0;$i<count($resultUid);$i++){
                if($i==0){
                    $uidstr.=$resultUid[$i];
                }else{
                    $uidstr.=','.$resultUid[$i];
                }

            }
            $uidstr.=')';
            $sql .= " and id in " . $uidstr . "";
        }
        if ($street) {
            $sql .= " and street like '%" . $street . "%'";

        }
        if ($shop) {
            $sql .= " and shopName like '%" . $shop . "%'";
        }
        $data = M('Buyers')->query($sql);
        if($data){
            for($i=0;$i<count($data);$i++){
                $map2['uid']=$data[$i]['id'];
                $res =M('relationship')->where($map2)->find();
                if($res){
                    $data[$i]['sname']=$res['sname'];
                }else{
                    $data[$i]['sname']="";
                }
            }
        }
        if ($data) {
            $orderTable = M('order');
            $data1 = array('is_export' => 1);

            $args = array_map(function($src){
                return $src['orderid'];}, $data);
            $map['orderid']  = array('in',$args);
            $result = $orderTable->where($map)->setField($data1);
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";
            $headArr = array("编号","客户姓名","手机号","城市","街道","店铺","余额","创建时间","业务员");
            $this->getExcel($filename, $headArr, $data,null);
        }else{
            $this->error("没有可导出的数据");
        }

    }
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);
        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $objPHPExcel->getActiveSheet()->getStyle($colum . '2')->getFont()->setBold(true);
            $key += 1;
        }
        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $span++;
            }
            $column++;
        }
        $objActSheet->getColumnDimension('A')->setWidth(5);
        $objActSheet->getColumnDimension('B')->setWidth(16);
        $objActSheet->getColumnDimension('C')->setWidth(16);
        $objActSheet->getColumnDimension('D')->setWidth(10);
        $objActSheet->getColumnDimension('E')->setWidth(25);
        $objActSheet->getColumnDimension('F')->setWidth(20);
        $objActSheet->getColumnDimension('G')->setWidth(5);
        $objActSheet->getColumnDimension('H')->setWidth(20);
        $objActSheet->getColumnDimension('I')->setWidth(10);
        $objActSheet->getColumnDimension('J')->setWidth(60);
        $objActSheet->getColumnDimension('K')->setWidth(80);
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
    public function details(){
        $detail=I();
        $map["uid"]=$detail['uid'];
        $map["status"]=3000;
        $data['id']=$detail['uid'];
        $info=M("buyers")->where($data)->find();
        $sum=M("order")->where($map)->sum("amount");
        $res2=M('relationship')->where($map)->find();
        $sList=M('sale_man')->select();
        //订单详细
        $ordermMap["uid"]=$detail['uid'];
        $res=$this->listsM('order',$ordermMap,"");
        if($res2){
            $info['sname']=$res2['sname'];
        }else{
            $info['sname']="";
        }
        if($sum==NULL||$sum==0||$sum==""){
            $info['sum']=0;
        }else{
            $info['sum']=$sum;
        }

        sg_int_to_string_order($res);
        $this->assign("orderLists",$res);
        $this->relation=$info;
        $this->assign("sales",$sList);
        $this->display();
    }
    public function changeSname(){
        $map["uid"]=I("uid");
        $data["sname"]=I("sname");
        $data["sid"]=I("sid");
        $res=M("relationship")->where($map)->find();
        if($res){
            $result=D("relationship")->where($map)->save($data);
        }else{
            $data['uid']=I("uid");
            $result=D("relationship")->add($data);
        }
        if($result){
            echo "修改成功";
        }else{
            echo "修改成功，但没有变化";
        }
    }
    public function changePhone(){
        $map["uid"]=I("uid");
        $data["phone"]=I("phone");
        $result=D("buyers")->where($map)->save($data);
        if($result){
            echo "修改成功";
        }else{
            echo "修改成功，但没有变化";
        }
    }
    public function data($realName="",$limit=20,$export=0,$skip=0){
        $falg = I('flag');
        $sql="SELECT a.toName,a.uid,sum(a.amount) as sum ,count(a.orderid) as count FROM gr_order a where 1=1 and a.status>0 and a.status<4000  ";
        if($realName){
            $map['realName']=array('like',"%$realName%");
            $userlist=M('buyers')->where($map)->getField('id',true);
            $range='('.implode('',$userlist).')';
            $sql.=" and a.uid in $range";
        }
        if ($falg=="count"){
            $sql.=" GROUP BY a.uid order by count(a.*) desc limit ".$skip.",".$limit;
        }else{
            $sql.=" GROUP BY a.uid order by sum(a.amount) desc limit ".$skip.",".$limit;
        }
        $res = M("order")->query($sql);
        foreach($res as $k=>$v){
            $sql2="select sum(tdtotalprice) as tdtotal,uid from (select a.uid as uid,b.tdtotalprice as tdtotalprice from gr_order a,gr_reject b where a.orderid=b.oldorderid and a.uid=".$v['uid'].") as res group by uid";
            $dataList=M('order')->where(array('uid'=>$v['uid']))->order('createDate asc')->limit(1)->select();
            $rejectdata=M('reject')->query($sql2);
            $res[$k]['firstDate']=$dataList[0]['createDate'];
            $res[$k]['rejectData']=$rejectdata[0]['tdtotal'];
        }
        if($export==1){
            $data=[];
            foreach($res as $k=>$v){
                $data[$k]['toName']=$v['toName'];
                $data[$k]['sum']=$v['sum'];
                $data[$k]['rejectData']=$v['rejectData'];
                $data[$k]['rejectPer']=number_format($v['rejectData']*100/$v['sum'],2).'%';
                $data[$k]['count']=$v['count'];
                $data[$k]['firstDate']=date('Y-m-d',$v['firstDate']);
            }
            if ($data) {
                //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
                import("Org.Util.PHPExcel");
                import("Org.Util.PHPExcel.Writer.Excel5");
                import("Org.Util.PHPExcel.IOFactory.php");

                $filename = "output_order_excel";
                $headArr = array("客户姓名","总消费","退货总价","退货比例","订单数","首次下单日期");
                $this->getExcel($filename, $headArr, $data,null);
            }else{
                $this->error("没有可导出的数据");
            }
        }else{
            $this->assign("buyers",$res);
            $this->display();
        }
    }
    //余额流水展示
    public function amountFlow2(){
        $userid = $_REQUEST['uid'];
        $nickname = $_REQUEST['nickname'];
        $map["uid"]=$userid;
        $list = $this-> listsM("amount_flow",$map,'createtime desc');
        $this->assign('nickname',$nickname);
        $this->assign('amountFlows', $list);
        $this->display();
    }
    public function returnAmount(){
        $map["id"]=I("uid");
        $amount=I("amount");
        $mark=I("mark");
        $data['nickname']=get_nickname();
        $data['action']=$mark."变动".$amount;
        $data['objectuid']=$map["id"];
        $data['creattime']=time();
        $detail="(".$mark.")后台人工变动";
        if($amount > 0){
            $action = "incre";
        }else{
            $action = "decre";
        }
        $this->amountFlow(I("uid"),abs($amount),$action,$detail);
        if(D('buyers')->where($map)->setInc('amount',$amount)){
            echo "修改成功";
        }else{
            echo "修改失败";
        }
    }

    public function contractapplyindex($phone='',$realName='',$city='',$sname='',$status='',$export=0){
        $map['status']=array('between','-1,2');
        if ($phone) {
            $mapph['phone'] = array('like','%'.$phone.'%');
            $resph=M('buyers')->where($mapph)->find();
            $map['uid']=$resph['id'];
        }
        if ($realName) {
            $maprn['realName'] = array('like','%'.$realName.'%');
            $resrn=M('buyers')->where($maprn)->find();
            $map['uid']=$resrn['id'];
        }
        if ($city) {
            $mapcity['city'] = array('like','%'.$city.'%');
            $rescity=M('buyers')->where($mapcity)->select();
            $in_arr=[];
            foreach ($rescity as $k=>$v){
                $in_arr[]=$v['id'];
            }
            $map['uid']=array('in',$in_arr);
        }
        if ($sname) {
            $maprs['sname'] = array('like','%'.$sname.'%');
            $resrs=M('relationship')->where($maprs)->select();
            $in_arrs=[];
            foreach ($resrs as $k=>$v){
                $in_arrs[]=$v['uid'];
            }
            $map['uid']=array('in',$in_arrs);
        }
        if ($status!='') {
            if($status==999){
                $map['status'] = array('between','-1,2');
            }else{
                $map['status']=$status;
            }
        }
        if($export==1){
            $list = M('contractapply')->where($map)->order('createAt desc')->select();
        }else{
            $list = $this->lists('contractapply',$map ,'createAt desc');
        }
        for($i=0;$i<count($list);$i++){
            $mapa['id']=$list[$i]['uid'];
            $resa=M('buyers')->where($mapa)->find();
            $list[$i]['city']=$resa['city'];
            $list[$i]['realName']=$resa['realName'];
            $list[$i]['phone']=$resa['phone'];
            $list[$i]['street']=$resa['street'];
            $list[$i]['shopName']=$resa['shopName'];
            if($list[$i]['status']==0){
                $list[$i]['statusname']='未受理';
            }elseif($list[$i]['status']==1){
                $list[$i]['statusname']='未审核';
            }elseif($list[$i]['status']==2){
                $list[$i]['statusname']='已通过';
            }elseif($list[$i]['status']==-1){
                $list[$i]['statusname']='不通过';
            }
            $mapb['uid']=$list[$i]['uid'];
            $resb=M('relationship')->where($mapb)->find();
            if($resb){
                $list[$i]['sname']=$resb['sname'];
            }
        }
        if($export==1){
            $data=[];
            foreach ($list as $k=>$v){
                $dataArr=array(
                    'uid'=>$v['uid'],
                    'city'=>$v['city'],
                    'realName'=>$v['realName'],
                    'phone'=>$v['phone'],
                    'shopName'=>$v['shopName'],
                    'street'=>$v['street'],
                    'sname'=>$v['sname'],
                    'statusname'=>$v['statusname'],
                    'createAt'=>time_format($v['createAt']),
                );
                $data[]=$dataArr;
            }
            if ($data) {
                //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
                import("Org.Util.PHPExcel");
                import("Org.Util.PHPExcel.Writer.Excel5");
                import("Org.Util.PHPExcel.IOFactory.php");

                $filename = "合同列表";
                $headArr = array("UID", "城市", "姓名", "电话", "店铺名", "地址", "业务员", "状态", "创建时间");
                $title = "合同列表";
                $this->getExcel($filename, $headArr, $data, $title);
            }else{
                $this->error("没有可导出的数据！");
            }
        }else{
            $this->assign('_list',$list);
            $this->status=I('status');
            $this->display();
        }
    }
    public function newaccept(){
        $mapd['uid']=I('uid');
        $resd=M('relationship')->where($mapd)->find();
        if($resd){
            $data['status']=1;
            $data['kfId']=UID;
            $data['updateAt']=NOW_TIME;
            $data['acceptremark']=I('acceptremark');
            $model = M('contractapply');
            $id = $model->where($mapd)->save($data);
            if (!$id) {
                $this->error("操作失败1！");
            } else {
                addOrderLog(I('uid'), "会员审核受理", "客服受理了会员申请");
                $this->success('保存成功！', U('contractapplyindex'));
            }
        }else{
            $data['status']=1;
            $data['kfId']=UID;
            $data['updateAt']=NOW_TIME;
            $data['acceptremark']=I('acceptremark');
            $model = M('contractapply');
            $id = $model->where($mapd)->save($data);

            $mapsm['id']=I('id');
            $ressm=M('sale_man')->where($mapsm)->find();
            $datasm['uid']=I('uid');
            $datasm['sid']=$ressm['id'];
            $datasm['sname']=$ressm['name'];
            $datasm['createtime']=NOW_TIME;
            $idsm=M('relationship')->add($datasm);
            if (!$id || !$idsm) {
                $this->error("操作失败2！");
            } else {
                addOrderLog(I('uid'), "会员合同受理", "客服受理了会员申请");
                $this->success('保存成功！', U('contractapplyindex'));
            }
        }
    }
    public function acceptdetail(){
            $map['id']=I('uid');
            $res=M('buyers')->where($map)->find();
            $mapa['uid']=I('uid');
            $resa=M('contractapply')->where($mapa)->find();
            $res['chuangjian']=$resa['createAt'];
            $this->assign('data',$res);

            $mapc['uid']=I('uid');
            $resc=M('relationship')->where($mapc)->find();
            if($resc){
                $this->assign('exist',1);
                $this->assign('saleman',$resc);
            }else{
                $this->assign('exist',2);
                $resb=M('sale_man')->select();
                $this->assign('_list',$resb);
            }
            $mapd['dataId']=I('uid');
            $oplist=M('operate_log')->where($mapd)->select();
            $order['log'] = $oplist;
            $this->order = $order;

            $this->assign('uid',I('uid'));
            $this->display();
    }

    public function reviewdetail(){
        $map['id']=I('uid');
        $res=M('buyers')->where($map)->find();
        $mapa['uid']=I('uid');
        $resa=M('contractapply')->where($mapa)->find();
        $res['chuangjian']=$resa['createAt'];
        $res['acceptremark']=$resa['acceptremark'];
        $this->assign('data',$res);

        $mapc['uid']=I('uid');
        $resc=M('relationship')->where($mapc)->find();
        $this->assign('exist',1);
        $this->assign('saleman',$resc);
        $mapd['dataId']=I('uid');
        $oplist=M('operate_log')->where($mapd)->select();
        $order['log'] = $oplist;
        $this->order = $order;
        $this->assign('uid',I('uid'));
        $this->display();
    }

    public function newreview(){
        $mapd['uid']=I('uid');
        $data['status']=I('status');
        $data['kfId']=UID;
        $data['updateAt']=NOW_TIME;
        $data['reviewremark']=I('reviewremark');
        $model = M('contractapply');
        $id = $model->where($mapd)->save($data);

        $status=I('status');
        if($status==2){
            $datacl['contract_level']=1;
            $mapcl['id']=I('uid');
            M('buyers')->where($mapcl)->save($datacl);
        }
        if (!$id) {
            $this->error("操作失败2！");
        } else {
            addOrderLog(I('uid'), "会员合同审核", "客服审核了会员申请");
            $this->success('保存成功！', U('contractapplyindex'));
        }
    }

    public function completedetail(){
        $map['id']=I('uid');
        $res=M('buyers')->where($map)->find();
        $mapa['uid']=I('uid');
        $resa=M('contractapply')->where($mapa)->find();
        $res['chuangjian']=$resa['createAt'];
        $res['acceptremark']=$resa['acceptremark'];
        $res['reviewremark']=$resa['reviewremark'];
        if($resa['status']==2){
            $res['statusname']='通过';
        }elseif($resa['status']==-1){
            $res['statusname']='不通过';
        }
        $this->assign('data',$res);
        $mapc['uid']=I('uid');
        $resc=M('relationship')->where($mapc)->find();
        $this->assign('exist',1);
        $this->assign('saleman',$resc);
        $mapd['dataId']=I('uid');
        $oplist=M('operate_log')->where($mapd)->select();
        $order['log'] = $oplist;
        $this->order = $order;
        $this->assign('uid',I('uid'));
        $this->display();
    }



}
